package com.example.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.lang.Result;
import com.example.entity.Blog;
import com.example.service.BlogService;
import com.example.utils.ShiroUtil;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ylj
 * @since 2021-02-28
 */





@RestController
public class BlogController {


    @Autowired
    BlogService blogService;

    @GetMapping("/blogs")
    public Result list(@RequestParam(defaultValue = "1") Integer currentPage) {

        Page page = new Page(currentPage, 4);
        IPage pageData = blogService.page(page, new QueryWrapper<Blog>().orderByDesc("created"));
        return Result.succ(pageData);
    }
    @GetMapping("/myblogs")
    public Result myblogs(@RequestParam(defaultValue = "1") Integer currentPage) {

        Page page = new Page(currentPage, 4);
        IPage pageData = blogService.page(page, (new QueryWrapper<Blog>().like("user_id", "admin")));
        return Result.succ(pageData);
    }
    @GetMapping("/blog/{id}")
    public Result detail(@PathVariable(name = "id") Long id) {
        Blog blog = blogService.getById(id);
        Assert.notNull(blog, "该博客已被删除");
        return Result.succ(blog);
    }

    @GetMapping("/blog/search/wd={wd}")
    public Result search(@PathVariable(name = "wd") String wd) {
        //size返回是几组数据
        List blog = blogService.list(new QueryWrapper<Blog>().like("title", wd));

        Assert.notNull(blog, "无哦");
        return Result.succ(blog);
    }
    @GetMapping("/blog/search/userId={wd}")
    public Result userId(@PathVariable(name = "wd") String wd) {
        //size返回是几组数据
        List blog = blogService.list(new QueryWrapper<Blog>().like("user_id", wd));

        Assert.notNull(blog, "无哦");
        return Result.succ(blog);
    }

    @GetMapping("/blog/groups")
    public  Result fenzu() {
        List<Blog> items = blogService.list(null);// 获取了表中所有数据
        List<String> nameList = items.stream().map(Blog::getGroups).collect(Collectors.toList());// 取出其中一列  泛型
//        Long[] longArr = new Long[nameList.size()];

//        nameList.toArray(longArr);    //nameList 数据放进 LongArr 即转换为转组

        //nameList去重
        List<String> list = new ArrayList<String>();
        for (int i=0; i<nameList.size(); i++) {
            if(!list.contains(nameList.get(i))) {
                list.add(nameList.get(i));
            }
        }


        HashMap map = new HashMap();


        for(int i=0;i<list.size();i++)
        {
         String t = list.get(i);

        List blog = blogService.list(new QueryWrapper<Blog>().eq("groups", t));

        map.put(t, blog);

        }


        return Result.succ(map);
    }


    /**
     * 文章删除
     * @param id
     * @return
     */
    @GetMapping("/blog/delete/{id}")
    public Result delete(@PathVariable(name = "id")String id){
        boolean result = blogService.removeById(id);// 据库中为Long id
//        boolean result = true;// 据库中为Long id
        Assert.isTrue(result,"本文章已被删除");
        return Result.succ("成功删除本文章");
    }
//    @RequiresAuthentication  //需要登录认证

    @PostMapping("/blog/edit")
    public Result edit(@Validated @RequestBody Blog blog) {
        //@Validated 内容不能为空
//        Assert.isTrue(false, "公开版不能任意编辑！");

        Blog temp = null;
        if(blog.getId() != null) {
            temp = blogService.getById(blog.getId());              //查询数据表
            // 只能编辑自己的文章
            System.out.println(ShiroUtil.getProfile().getId());
//            Assert.isTrue(temp.getUserId() == ShiroUtil.getProfile().getUsername(),  temp.getUserId()+"+"+ShiroUtil.getProfile().getUsername()+"没有权限编辑");
//.longValue() long 类型封装问题   不然不相等
        } else {

            temp = new Blog();
            temp.setUserId((ShiroUtil.getProfile().getUsername()));
            temp.setCreated(LocalDateTime.now());
            temp.setDescription(null);
            temp.setStatusd(0);
//          temp.setId(ShiroUtil.getProfile().getId());
        }

        BeanUtil.copyProperties(blog, temp,"id","userId", "created", "status");


        blogService.saveOrUpdate(temp);

//        return Result.mul(blog,temp);
        return Result.succ(temp);
    }
}
